extends Control
class_name ItemInventory

# 物品栏系统
# 显示和管理玩家的道具、装备等物品

signal item_selected(item_data: Dictionary)
signal item_used(item_data: Dictionary)

# 物品栏配置
const SLOT_SIZE = Vector2(32, 32)
const SLOT_SPACING = 8
const SLOTS_PER_ROW = 8
const MAX_ROWS = 6

# UI节点
var inventory_panel: Panel
var grid_container: GridContainer
var item_slots: Array[ItemSlot] = []

# 物品数据
var items: Array[Dictionary] = []

class ItemSlot extends Control:
	var slot_bg: NinePatchRect
	var item_icon: TextureRect
	var item_data: Dictionary
	var quantity_label: Label
	
	signal slot_clicked(slot: ItemSlot)
	
	func _init():
		size = SLOT_SIZE
		
		# 创建槽位背景
		slot_bg = NinePatchRect.new()
		add_child(slot_bg)
		slot_bg.texture = load("res://Art/v1.1 dungeon crawler 16X16 pixel pack/ui (new)/health_ui.png")
		slot_bg.size = SLOT_SIZE
		slot_bg.modulate = Color(0.3, 0.3, 0.3, 0.8)
		
		# 创建物品图标
		item_icon = TextureRect.new()
		add_child(item_icon)
		item_icon.size = SLOT_SIZE - Vector2(4, 4)
		item_icon.position = Vector2(2, 2)
		item_icon.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
		
		# 创建数量标签
		quantity_label = Label.new()
		add_child(quantity_label)
		quantity_label.size = Vector2(20, 12)
		quantity_label.position = Vector2(SLOT_SIZE.x - 20, SLOT_SIZE.y - 12)
		quantity_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
		quantity_label.vertical_alignment = VERTICAL_ALIGNMENT_BOTTOM
		quantity_label.add_theme_color_override("font_color", Color.WHITE)
		quantity_label.add_theme_color_override("font_shadow_color", Color.BLACK)
		quantity_label.add_theme_constant_override("shadow_offset_x", 1)
		quantity_label.add_theme_constant_override("shadow_offset_y", 1)
		quantity_label.add_theme_font_size_override("font_size", 8)
		
		# 添加抗锯齿字体
		var slot_font = SystemFont.new()
		slot_font.font_names = ["Arial", "Microsoft YaHei", "SimSun"]
		slot_font.antialiasing = TextServer.FONT_ANTIALIASING_GRAY
		slot_font.hinting = TextServer.HINTING_LIGHT
		quantity_label.add_theme_font_override("font", slot_font)
	
	func _gui_input(event):
		if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
			slot_clicked.emit(self)
	
	func set_item(data: Dictionary):
		item_data = data
		if data.is_empty():
			clear_slot()
		else:
			item_icon.texture = load(data.get("icon_path", ""))
			quantity_label.text = str(data.get("quantity", 1)) if data.get("quantity", 1) > 1 else ""
			item_icon.visible = true
	
	func clear_slot():
		item_data = {}
		item_icon.texture = null
		item_icon.visible = false
		quantity_label.text = ""

func _ready():
	initialize()

func initialize():
	# 设置物品栏尺寸
	var total_width = (SLOT_SIZE.x + SLOT_SPACING) * SLOTS_PER_ROW - SLOT_SPACING + 20
	var total_height = (SLOT_SIZE.y + SLOT_SPACING) * MAX_ROWS - SLOT_SPACING + 60
	
	size = Vector2(total_width, total_height)
	
	# 如果没有设置锚点，则手动居中显示
	if anchor_left == 0.0 and anchor_right == 0.0:
		var viewport = get_viewport()
		var screen_size = viewport.get_visible_rect().size
		position = Vector2((screen_size.x - size.x) / 2, (screen_size.y - size.y) / 2)
	
	create_inventory_panel()
	create_item_slots()

func create_inventory_panel():
	# 创建物品栏背景面板
	inventory_panel = Panel.new()
	add_child(inventory_panel)
	inventory_panel.size = size
	inventory_panel.add_theme_color_override("bg_color", Color(0.1, 0.1, 0.1, 0.8))
	
	# 创建抗锯齿字体
	var clear_font = SystemFont.new()
	clear_font.font_names = ["Arial", "Microsoft YaHei", "SimSun"]
	clear_font.antialiasing = TextServer.FONT_ANTIALIASING_GRAY
	clear_font.hinting = TextServer.HINTING_LIGHT
	
	# 添加标题
	var title_label = Label.new()
	inventory_panel.add_child(title_label)
	title_label.text = "物品栏 (按I键关闭)"
	title_label.position = Vector2(10, 10)
	title_label.add_theme_color_override("font_color", Color.WHITE)
	title_label.add_theme_color_override("font_shadow_color", Color.BLACK)
	title_label.add_theme_constant_override("shadow_offset_x", 1)
	title_label.add_theme_constant_override("shadow_offset_y", 1)
	title_label.add_theme_font_size_override("font_size", 10)
	title_label.add_theme_font_override("font", clear_font)
	
	# 添加操作提示
	var help_label = Label.new()
	inventory_panel.add_child(help_label)
	help_label.text = "左键选择 / 右键使用物品"
	help_label.position = Vector2(10, 25)
	help_label.add_theme_color_override("font_color", Color.LIGHT_GRAY)
	help_label.add_theme_color_override("font_shadow_color", Color.BLACK)
	help_label.add_theme_constant_override("shadow_offset_x", 1)
	help_label.add_theme_constant_override("shadow_offset_y", 1)
	help_label.add_theme_font_size_override("font_size", 8)
	help_label.add_theme_font_override("font", clear_font)

func create_item_slots():
	# 创建网格容器
	grid_container = GridContainer.new()
	inventory_panel.add_child(grid_container)
	grid_container.columns = SLOTS_PER_ROW
	grid_container.position = Vector2(10, 40)
	grid_container.size = Vector2(size.x - 20, size.y - 50)
	
	# 创建物品槽
	for i in range(SLOTS_PER_ROW * MAX_ROWS):
		var slot = ItemSlot.new()
		grid_container.add_child(slot)
		slot.slot_clicked.connect(_on_slot_clicked)
		item_slots.append(slot)

func add_item(item_data: Dictionary) -> bool:
	# 检查是否可以堆叠
	if item_data.get("stackable", false):
		for slot in item_slots:
			if not slot.item_data.is_empty() and slot.item_data.get("id") == item_data.get("id"):
				slot.item_data["quantity"] = slot.item_data.get("quantity", 1) + item_data.get("quantity", 1)
				slot.set_item(slot.item_data)
				return true
	
	# 找到空槽位
	for slot in item_slots:
		if slot.item_data.is_empty():
			slot.set_item(item_data)
			items.append(item_data)
			return true
	
	return false  # 物品栏已满

func remove_item(item_id: String, quantity: int = 1) -> bool:
	for slot in item_slots:
		if not slot.item_data.is_empty() and slot.item_data.get("id") == item_id:
			var current_quantity = slot.item_data.get("quantity", 1)
			if current_quantity > quantity:
				slot.item_data["quantity"] = current_quantity - quantity
				slot.set_item(slot.item_data)
			else:
				slot.clear_slot()
				items.erase(slot.item_data)
			return true
	return false

func _on_slot_clicked(slot: ItemSlot):
	if not slot.item_data.is_empty():
		item_selected.emit(slot.item_data)
		
		# 右键使用物品
		if Input.is_action_pressed("ui_accept"):
			use_item(slot.item_data)

func use_item(item_data: Dictionary):
	if item_data.get("consumable", false):
		item_used.emit(item_data)
		remove_item(item_data.get("id", ""), 1)

# 创建预设物品数据示例
func create_sample_items():
	var sample_items = [
		{
			"id": "potion_red",
			"name": "红色药水",
			"icon_path": "res://Art/v1.1 dungeon crawler 16X16 pixel pack/props_itens/potion_red.png",
			"stackable": true,
			"consumable": true,
			"quantity": 3
		},
		{
			"id": "key_silver",
			"name": "银钥匙",
			"icon_path": "res://Art/v1.1 dungeon crawler 16X16 pixel pack/props_itens/key_silver.png",
			"stackable": false,
			"consumable": false,
			"quantity": 1
		},
		{
			"id": "bag_coins",
			"name": "金币袋",
			"icon_path": "res://Art/v1.1 dungeon crawler 16X16 pixel pack/props_itens/bag_coins.png",
			"stackable": true,
			"consumable": false,
			"quantity": 5
		}
	]
	
	for item in sample_items:
		add_item(item) 